package cn.rebeater.navigationclient;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.*;

public class DeviceListActivity extends Activity {

    private BluetoothAdapter mbtadapter = null;
    private ArrayAdapter<String> mdevicearray = null;

    private final int REQUEST_OPEN_BLUETOOTH = 1;
    private String TAG = "mydebug DeviceListActivity";
    public static String EXTRA_DEVICE_NAME = "devicename";
    private ProgressBar mLoadingIndicator;
    private TextView mstatus = null;

    /*
    TODO
     */

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_device_list);

        /* 防止用户返回 */
        setResult(Activity.RESULT_CANCELED);

        /* 视图控件 */
        Button btrescan = findViewById(R.id.rescan);
        btrescan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doDiscovery();
            }
        });

        Button btstopscan = findViewById(R.id.stopscan);
        mLoadingIndicator = findViewById(R.id.pb_loading_indicator);

        btstopscan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i(TAG, "onClick: STOP scan");
                if (mbtadapter.isDiscovering()) {
                    /*
                    TODO 修改loading状态
                     */
                    mLoadingIndicator.setVisibility(View.INVISIBLE);
                    mbtadapter.cancelDiscovery();
                    if(mdevicearray.getCount()==0)
                    {
                        mstatus.setText("未搜索到设备");
                    }
                    else
                    {
                        mstatus.setText("搜索到以下设备，请选择设备连接");
                    }
                }
            }
        });

        /* 状态栏 */
        mstatus = findViewById(R.id.status);

        /* 设备列表 */
        ListView mdevicelist;
        mdevicelist = findViewById(R.id.devicelist);
        mdevicearray = new ArrayAdapter<>(this, R.layout.device_name);
        mdevicelist.setAdapter(mdevicearray);
        mdevicelist.setOnItemClickListener(mdevicelistlistener);

        /* 蓝夜搜索设置 */
        /* 注册发现蓝牙设备广播 */
        this.registerReceiver(mreceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));

        /* 注册蓝牙搜索完成广播 */
        this.registerReceiver(mreceiver, new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED));

        /* 注册蓝牙搜索开始广播 */
        this.registerReceiver(mreceiver, new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED));
    }

    @Override
    protected void onStart() {
        super.onStart();

        /* 获取蓝牙适配器 */
        mbtadapter = BluetoothAdapter.getDefaultAdapter();
        if (!mbtadapter.isEnabled()) {
            Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(intent, REQUEST_OPEN_BLUETOOTH);
            return;
        }
        doDiscovery();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent
            data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_OPEN_BLUETOOTH) {
            /* 如果蓝牙设备打开，则开始搜索设备 */
            if (resultCode == Activity.RESULT_OK) {
                doDiscovery();
            } else {
                endActivity(Activity.RESULT_CANCELED, null);
            }
        }
    }

    private void endActivity(int resultcode, String value) {
        /* 创建意图，传递蓝牙设备名 */
        Intent intent = new Intent();
        if (resultcode == Activity.RESULT_OK) {
            intent.putExtra(EXTRA_DEVICE_NAME, value);
        }

        /* 设置结果结束活动 */
        setResult(resultcode, intent);
        finish();
    }

    private void doDiscovery() {
        /* 开始扫描蓝牙设备 */
        Log.i(TAG, "doDiscovery: ");
        mLoadingIndicator.setVisibility(View.VISIBLE);
        if (mbtadapter.isDiscovering()) {
            mbtadapter.cancelDiscovery();
        }
        mbtadapter.startDiscovery();

        /* 清除设备列表 */
        mdevicearray.clear();
    }

    private ListView.OnItemClickListener mdevicelistlistener = new ListView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            /* 停止搜索设备 */
            mLoadingIndicator.setVisibility(View.INVISIBLE);
            if (mbtadapter.isDiscovering()) {
                mbtadapter.cancelDiscovery();
            }

            String device = ((TextView) view).getText().toString();
            endActivity(Activity.RESULT_OK, device);
        }
    };

    private final BroadcastReceiver mreceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
//                /* 获取发现蓝牙设备信息 */
                BluetoothDevice btdevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                String devicename=btdevice.getName();
                /*
                TODO 防止没搜到闪退
                 */
                if(null!=devicename) {
//                    if (btdevice.getName().contains("BT-T")) {
                        mdevicearray.add(btdevice.getName() + "\n" + btdevice.getAddress());
//                    }
                }
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals
                    (action)) {
                if (mdevicearray.getCount() == 0) {
                    mstatus.setText("未搜索到设备");
                }
            }
            else if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)){
                mstatus.setText("设备搜索中, 请选择设备连接!");
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();

        /* 先注销蓝牙广播, 取消搜索会触发搜索完成广播 */
        this.unregisterReceiver(mreceiver);

        if (mbtadapter != null) {
            mbtadapter.cancelDiscovery();
        }

        mdevicearray.clear();
    }
}
